package cn.edu.ccibe.exam16system.service.impl;

import cn.edu.ccibe.exam16system.entity.DormitoryDto;
import cn.edu.ccibe.exam16system.entity.Student;
import cn.edu.ccibe.exam16system.mapper.StudentMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edu.ccibe.exam16system.entity.Dormitory;
import cn.edu.ccibe.exam16system.service.DormitoryService;
import cn.edu.ccibe.exam16system.mapper.DormitoryMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 19370_d9m1awp
 * @description 针对表【t_dormitory】的数据库操作Service实现
 * @createDate 2025-04-18 08:58:10
 */
@Service
public class DormitoryServiceImpl extends ServiceImpl<DormitoryMapper, Dormitory>
        implements DormitoryService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public IPage<DormitoryDto> pageDorm(Page<Dormitory> pageInfo) {
        List<Student> studentList = studentMapper.selectList(null);
        Page<Dormitory> page = page(pageInfo);
        IPage<DormitoryDto> dtoPage = new Page<>();
        Map<String, List<Student>> studentMap = new HashMap<>();
        for (Student student : studentList) {
            List<Student> sList = studentMap.getOrDefault(student.getDormId(), new ArrayList<>());
            sList.add(student);
            studentMap.put(student.getDormId(), sList);
        }
        List<DormitoryDto> dtoList = new ArrayList<>();
        for (Dormitory item : page.getRecords()) {
            DormitoryDto dto = new DormitoryDto(item);
            List<Student> students = studentMap.get(item.getDormId().toString());
            if (students == null) {
                dto.setStudents(new ArrayList<>());
            } else {
                dto.setStudents(studentMap.get(item.getDormId().toString()));
            }
            dtoList.add(dto);
        }
        dtoPage.setPages(page.getPages());
        dtoPage.setCurrent(page.getCurrent());
        dtoPage.setSize(page.getSize());
        dtoPage.setTotal(page.getTotal());
        dtoPage.setRecords(dtoList);
        return dtoPage;
    }
}
